<template>
  <div>
    <el-dialog
      append-to-body
      :title="title"
      :width="width"
      :visible.sync="innerDialogVisible"
      :close-on-click-modal="false"
      @close="close"
    >
      <el-row v-if="action === 'create'" :gutter="20">
        <!-- 左侧表单区域 -->
        <el-col :span="14">
          <el-form :model="temp" :rules="rules" label-position="left" label-width="100px">
            <el-form-item label="客户名称" prop="name">
              <el-input v-model="temp.name" />
            </el-form-item>
            <el-form-item label="WhatsApp" prop="whatsapp">
              <el-input v-model="temp.whatsapp">
                <el-button slot="append" icon="el-icon-search" @click="handleSearchCustomer('whatsapp', temp.whatsapp)" />
              </el-input>
            </el-form-item>
            <el-form-item label="客户类型" prop="source">
              <el-select v-model="temp.crmcustomercategory_id" placeholder="请选择">
                <el-option
                  v-for="item in customer_categories"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="公司名称" prop="company">
              <el-input v-model="temp.company" />
            </el-form-item>
            <el-form-item label="标签" prop="tag">
              <div class="tag-section">
                <el-select v-model="selectedTagCategory" placeholder="选择标签类别" style="width: 150px; margin-right: 10px">
                  <el-option
                    v-for="(category, key) in tagOptions"
                    :key="key"
                    :label="category.label"
                    :value="key"
                  />
                </el-select>

                <el-select
                  v-if="selectedTagCategory"
                  v-model="inputValue"
                  placeholder="选择标签"
                  style="width: 200px"
                  @change="handleTagSelect"
                >
                  <el-option
                    v-for="option in tagOptions[selectedTagCategory].options"
                    :key="option"
                    :label="option"
                    :value="option"
                  />
                </el-select>
              </div>

              <div class="tag-display" style="margin-top: 10px">
                <el-tag
                  v-for="tag in temp.tag"
                  :key="tag"
                  closable
                  :disable-transitions="false"
                  style="margin-right: 10px; margin-bottom: 5px"
                  @close="handleClose(tag)"
                >
                  {{ tag }}
                </el-tag>
              </div>

              <el-button class="button-new-tag" size="small" style="margin-top: 10px" @click="showInput">+ 自定义标签</el-button>
              <el-input
                v-if="inputVisible"
                ref="saveTagInput"
                v-model="customInputValue"
                class="input-new-tag"
                size="small"
                style="width: 200px"
                @keyup.enter.native="handleCustomInputConfirm"
                @blur="handleCustomInputConfirm"
              />
            </el-form-item>
            <el-form-item label="域名" prop="domain">
              <el-input v-model="temp.domain" />
            </el-form-item>
            <el-form-item label="邮箱地址" prop="mail">
              <el-input v-model="temp.mail" />
            </el-form-item>
            <el-form-item label="电话号码" prop="phone">
              <el-input v-model="temp.phone">
                <el-button slot="append" icon="el-icon-search" @click="handleSearchCustomer('phone', temp.phone)" />
              </el-input>
            </el-form-item>
            <el-form-item label="国家" prop="country">
              <el-select v-model="temp.country" filterable placeholder="请选择">
                <el-option
                  v-for="item in countries"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="客户来源" prop="source">
              <el-select v-model="temp.source" placeholder="请选择">
                <el-option
                  v-for="item in customer_sources"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="地址" prop="address">
              <el-input v-model="temp.address" type="textarea" />
            </el-form-item>
            <el-form-item label="备注" prop="address">
              <el-input v-model="temp.note" type="textarea" />
            </el-form-item>

            <el-form-item v-if="this.$store.getters.roles.indexOf('sales_manager') !== -1" label="负责人" prop="owner_id">
              <el-select v-model="temp.owner_id" placeholder="请选择负责人" filterable>
                <el-option
                  v-for="user in usersList"
                  :key="user.id"
                  :label="user.first_name + user.last_name || user.username"
                  :value="user.id"
                />
              </el-select>
            </el-form-item>
          </el-form>
        </el-col>

        <!-- 右侧AI信息提取区域 -->
        <el-col :span="10">
          <div class="ai-extract-section">
            <h4 class="ai-section-title">
              <i class="el-icon-magic-stick" />
              AI信息提取助手
            </h4>
            <!-- 粘贴上传区域 -->
            <div
              v-loading="isUploading"
              class="paste-area"
              tabindex="0"
              @paste="handlePaste"
              @click="focusPasteArea"
              @dragover.prevent
              @dragenter="handleDragEnter"
              @dragleave="handleDragLeave"
              @drop="handleDrop"
            >
              <div v-if="!userInfoInput" class="paste-tip">
                <i class="el-icon-picture-outline" />
                <div>点击此区域，然后 Ctrl+V 粘贴图片或输入文本信息</div>
              </div>
              <el-input
                ref="userInfoTextarea"
                v-model="userInfoInput"
                type="textarea"
                placeholder="请输入客户信息或直接粘贴/拖拽图片&#10;&#10;文本示例：&#10;John Smith, ABC Manufacturing Ltd&#10;Email: john@abcmfg.com, Phone: +1-555-123-4567&#10;Address: 123 Industrial Ave, New York, NY 10001, USA&#10;&#10;图片支持：Ctrl+V 粘贴图片 | 拖拽图片到此区域"
                :rows="5"
                style="margin-bottom: 10px;"
              />
              <div v-if="isDragging" class="input-overlay">
                <i class="el-icon-upload" />
                <span>松开鼠标上传图片</span>
              </div>
            </div>
            <div class="ai-tip">
              <i class="el-icon-info" />
              <span>支持多种输入方式：①直接输入文本信息 ②粘贴图片(Ctrl+V) ③拖拽图片到输入框 - AI将自动提取客户信息</span>
            </div>
            <div style="text-align: center;">
              <el-button
                type="primary"
                icon="el-icon-magic-stick"
                :disabled="!userInfoInput.trim()"
                size="small"
                @click="handleStartExtract"
              >
                提取客户信息
              </el-button>
            </div>
            <AITask
              ref="aiExtractTask"
              :params="{ user_info: userInfoInput }"
              task-name="task_extract_customer_info_from_userinfo"
              show-name="提取客户信息"
              dialog-title="AI客户信息提取"
              dialog-width="60%"
              :show-apply-button="false"
              style="display: none;"
              @final-result="handleExtractResult"
              @close="handleAITaskClose"
            />
          </div>
        </el-col>
      </el-row>

      <!-- 编辑模式或其他操作时使用普通表单布局 -->
      <el-form v-else :model="temp" :rules="rules" label-position="left" label-width="100px">
        <el-form-item label="客户名称" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="WhatsApp" prop="whatsapp">
          <el-input v-model="temp.whatsapp">
            <el-button slot="append" icon="el-icon-search" @click="handleSearchCustomer('whatsapp', temp.whatsapp)" />
          </el-input>
        </el-form-item>
        <el-form-item label="客户类型" prop="source">
          <el-select v-model="temp.crmcustomercategory_id" placeholder="请选择">
            <el-option
              v-for="item in customer_categories"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="公司名称" prop="company">
          <el-input v-model="temp.company" />
        </el-form-item>
        <el-form-item label="标签" prop="tag">
          <div class="tag-section">
            <el-select v-model="selectedTagCategory" placeholder="选择标签类别" style="width: 150px; margin-right: 10px">
              <el-option
                v-for="(category, key) in tagOptions"
                :key="key"
                :label="category.label"
                :value="key"
              />
            </el-select>

            <el-select
              v-if="selectedTagCategory"
              v-model="inputValue"
              placeholder="选择标签"
              style="width: 200px"
              @change="handleTagSelect"
            >
              <el-option
                v-for="option in tagOptions[selectedTagCategory].options"
                :key="option"
                :label="option"
                :value="option"
              />
            </el-select>
          </div>

          <div class="tag-display" style="margin-top: 10px">
            <el-tag
              v-for="tag in temp.tag"
              :key="tag"
              closable
              :disable-transitions="false"
              style="margin-right: 10px; margin-bottom: 5px"
              @close="handleClose(tag)"
            >
              {{ tag }}
            </el-tag>
          </div>

          <el-button class="button-new-tag" size="small" style="margin-top: 10px" @click="showInput">+ 自定义标签</el-button>
          <el-input
            v-if="inputVisible"
            ref="saveTagInput"
            v-model="customInputValue"
            class="input-new-tag"
            size="small"
            style="width: 200px"
            @keyup.enter.native="handleCustomInputConfirm"
            @blur="handleCustomInputConfirm"
          />
        </el-form-item>
        <el-form-item label="域名" prop="domain">
          <el-input v-model="temp.domain" />
        </el-form-item>
        <el-form-item label="邮箱地址" prop="mail">
          <el-input v-model="temp.mail" />
        </el-form-item>
        <el-form-item label="电话号码" prop="phone">
          <el-input v-model="temp.phone">
            <el-button slot="append" icon="el-icon-search" @click="handleSearchCustomer('phone', temp.phone)" />
          </el-input>
        </el-form-item>
        <el-form-item label="国家" prop="country">
          <el-select v-model="temp.country" filterable placeholder="请选择">
            <el-option
              v-for="item in countries"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="客户来源" prop="source">
          <el-select v-model="temp.source" placeholder="请选择">
            <el-option
              v-for="item in customer_sources"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="地址" prop="address">
          <el-input v-model="temp.address" type="textarea" />
        </el-form-item>
        <el-form-item label="备注" prop="address">
          <el-input v-model="temp.note" type="textarea" />
        </el-form-item>

        <el-form-item v-if="this.$store.getters.roles.indexOf('sales_manager') !== -1" label="负责人" prop="owner_id">
          <el-select v-model="temp.owner_id" placeholder="请选择负责人" filterable>
            <el-option
              v-for="user in usersList"
              :key="user.id"
              :label="user.first_name + user.last_name || user.username"
              :value="user.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="innerDialogVisible = false">取 消</el-button>
        <el-button :type="action !== 'delete'?'primary':'danger'" :loading="saveloading" @click="confirm">保 存</el-button>
        <el-button v-if="temp.id" type="primary" @click="handleBind">绑 定</el-button>
      </span>
    </el-dialog>
    <crmneworder
      :crmcustomer_id="customer.id"
      :crmcustomer__name="customer.name"
      :is-visible="newOrderVisible"
      @close="newOrderVisible=false"
    />
  </div>
</template>

<script>
import { Get, Post, Put, Delete } from '@/api/crm/crmcustomer'
import { GetCustomerCategories } from '@/api/crm/crmm'
import { CRMGetProjectUsers as GetUsers } from '@/api/crm/crmmanage'
import qs from 'qs'
import { countries, customer_source, getCountryLabel, rules } from '../../../api/crm/crmcommon'
import Crmneworder from './crmneworder'
import AITask from '@/components/AITask'
export default {
  name: 'Crmeditcustomer',
  components: { Crmneworder, AITask },
  props: ['customer_row', 'isVisible', 'doaction'],
  data() {
    return {
      rules: rules,
      customer: {
        id: '',
        name: '',
        crmcustomercategory_id: '',
        country: '',
        remarks: [],
        mails: [],
        attachments: []
      },
      inputVisible: false,
      inputValue: '',
      newOrderVisible: false,
      data: [],
      listLoading: false,
      getCountryLabel: getCountryLabel,
      kwInput: '',
      order_by: '',
      order_desc: '',
      // pagination
      pagesize: 10,
      page: 1,
      total: 0,
      countries: countries,
      customer_sources: customer_source,
      action: null,
      dialogVisible: false,
      title: '',
      temp: {
        name: '', // The name of the customer
        crmcustomercategory_id: '', // The category of the customer
        company: '', // The company name of the customer
        domain: '', // Domain name associated with the customer
        mail: '', // Email address of the customer
        phone: '', // Phone number of the customer
        tag: [],
        note: '',
        whatsapp: '', // WhatsApp number of the customer
        country: '', // Country of the customer
        source: '', // Source from where the customer was acquired
        address: '', // Physical address of the customer
        owner_id: null
      },
      width: '',
      innerDialogVisible: false,
      customer_categories: [],
      saveloading: false,
      selectedTagCategory: '',
      customInputValue: '',
      tagOptions: {
        requirementType: {
          label: '需求类型',
          options: ['定制设计', '成品加LOGO']
        },
        frequencyType: {
          label: '需求频率',
          options: ['新客户/试水', '高频订单/长期合作', '单次大额订单']
        },
        brandPosition: {
          label: '品牌定位',
          options: ['高端品牌', '中端品牌', '经济型品牌', '可持续发展品牌']
        },
        identity: {
          label: '身份',
          options: ['采购人员', '品牌创立者', '设计师']
        },
        clothingType: {
          label: '服装类型',
          options: ['瑜伽/普拉提', '健身服', '日常运动服', '骑行服', '马术服', '钓鱼服', '高尔夫', '赛车服', '工作服', '球类服装']
        },
        communicationType: {
          label: '沟通性格',
          options: ['细节控/完美主义者', '高效直接型', '犹豫型/需要更多确认']
        }
      },
      usersList: [],
      userInfoInput: '',
      isDragging: false,
      isUploading: false
    }
  },
  watch: {
    isVisible(v) {
      console.log(this.customer_row)
      this.innerDialogVisible = v
      this.action = this.doaction
      this.handleAction(this.action, this.customer_row)
    }
  },
  created() {
  // 在组件创建时获取一次客户分类数据
    this.handleGetCustomerCategories()
    this.getUsersList()
  },
  mounted() {
    // 组件挂载完成
  },
  beforeDestroy() {
    // 组件销毁前清理
  },
  methods: {
    handleTagSelect(value) {
      if (value && !this.temp.tag.includes(value)) {
        this.temp.tag.push(value)
      }
      this.inputValue = '' // 重置选择
    },

    handleCustomInputConfirm() {
      const inputValue = this.customInputValue
      if (inputValue && !this.temp.tag.includes(inputValue)) {
        this.temp.tag.push(inputValue)
      }
      this.inputVisible = false
      this.customInputValue = ''
    },
    handleBind() {
      this.$emit('bind', this.temp)
    },
    handleGetCustomerCategories() {
      GetCustomerCategories().then(response => {
        this.customer_categories = response.data.data
      })
    },
    handleSearchCustomer(field, value) {
      Get(null, qs.stringify({
        [field]: value,
        pagesize: this.pagesize,
        page: this.page,
        order_by: this.order_by,
        order_desc: this.order_desc
      }))
        .then(response => {
          // 如果返回数据data.data大于 1，取第一个
          if (response.data.data.length > 0) {
            this.temp = response.data.data[0]
          } else {
          // 提示没有找到匹配用户
            this.$notify({
              title: '提示',
              message: '没有找到匹配用户',
              type: 'warning',
              duration: 2000
            })
          }
        }).catch(err => {
          console.log(err)
          this.listLoading = false
        })
    },
    handleClose(tag) {
      this.temp.tag.splice(this.temp.tag.indexOf(tag), 1)
    },

    showInput() {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    handleInputConfirm() {
      const inputValue = this.inputValue
      if (inputValue) {
        this.temp.tag.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    },
    close() {
      this.innerDialogVisible = false
      // 重置AI输入框
      this.userInfoInput = ''
      // 重置loading状态
      this.saveloading = false
      this.isUploading = false
      this.isDragging = false
      this.$emit('close', true)
    },
    resetTemp() {
      this.temp = {
        name: '', // The name of the customer
        company: '', // The company name of the customer
        domain: '', // Domain name associated with the customer
        mail: '', // Email address of the customer
        phone: '', // Phone number of the customer
        tag: [], // 确保tag是数组格式
        note: '',
        whatsapp: '', // WhatsApp number of the customer
        country: '', // Country of the customer
        source: '', // Source from where the customer was acquired
        address: '', // Physical address of the customer
        owner_id: null
      }
    },
    getList() {
      this.listLoading = true
      Get(null, qs.stringify({
        kw: this.kwInput,
        pagesize: this.pagesize,
        page: this.page,
        order_by: this.order_by,
        order_desc: this.order_desc
      }))
        .then(response => {
          this.scrollTop()
          this.data = response.data.data
          this.listLoading = false
          this.total = response.data.total
        }).catch(err => {
          console.log(err)
          this.listLoading = false
        })
    },
    handleAction(action, row) {
      this.action = action
      switch (action) {
        case 'create':
          this.width = '50%'
          this.title = '添加新客户资料'
          this.resetTemp()
          break
        case 'delete':
          this.width = '30%'
          this.title = `确认要删除客户:${row.name}?`
          this.temp = Object.assign({}, row)
          break
        case 'edit':
          this.width = '50%'
          this.title = `修改客户:${row.name}`
          // 确保所有字段都被正确复制，包括owner_id
          Object.keys(this.temp).forEach(key => {
            if (row[key] !== undefined) this.temp[key] = row[key]
          })
          this.temp.id = row.id
          // 额外处理owner_id字段，确保它被正确设置
          if (row.owner_id !== undefined) {
            this.temp.owner_id = row.owner_id
          }
          console.log('编辑客户数据，owner_id:', this.temp.owner_id, '原始数据:', row)
          break
      }
    },
    confirm() {
      const _data = this.temp
      if (this.action === 'bind' && !this.temp.id) {
        this.action = 'create'
      }
      switch (this.action) {
        case 'create':
          if (this.temp.id) {
            delete this.temp.id
          }
          this.saveloading = true
          Post(_data).then(response => {
            this.customer = response.customer
            this.customer_row.id = response.customer.id
            this.notify('添加成功')
            this.$emit('bind', this.customer)
            this.newOrderVisible = true
            this.close()
            this.saveloading = false
          }).catch(error => {
            console.error('创建客户失败:', error)
            this.saveloading = false
            this.$notify({
              title: '错误',
              message: '创建客户失败: ' + (error.message || '未知错误'),
              type: 'error',
              duration: 3000
            })
          })
          break
        case 'delete':
          this.saveloading = true
          Delete(_data.id).then((response) => {
            this.getList()
            this.$emit('reload')
            this.notify('删除成功')
            this.close()
            this.saveloading = false
          }).catch(error => {
            console.error('删除客户失败:', error)
            this.saveloading = false
            this.$notify({
              title: '错误',
              message: '删除客户失败: ' + (error.message || '未知错误'),
              type: 'error',
              duration: 3000
            })
          })
          break
        case 'edit':
          this.saveloading = true
          Put(_data.id, _data).then((response) => {
            this.getList()
            this.notify('更新成功')
            this.close()
            this.saveloading = false
          }).catch(error => {
            console.error('更新客户失败:', error)
            this.saveloading = false
            this.$notify({
              title: '错误',
              message: '更新客户失败: ' + (error.message || '未知错误'),
              type: 'error',
              duration: 3000
            })
          })
          break
      }
    },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    // 点击搜索
    handleSearch() {
      this.page = 1
      this.getList()
    },
    getUsersList() {
      GetUsers(qs.stringify({
        pagesize: 100,
        page: 1
      })).then(response => {
        this.usersList = response.data.data || response.data || []
      }).catch(err => {
        console.log('获取用户列表失败:', err)
      })
    },
    handleExtractResult(result) {
      try {
        console.log('AI提取结果:', result)

        // 清理结果字符串，移除可能的多余字符
        let cleanResult = result.trim()

        // 移除可能的HTML注释标记或其他尾随字符
        if (cleanResult.includes('-->')) {
          cleanResult = cleanResult.substring(0, cleanResult.indexOf('-->'))
        }

        // 查找JSON对象的结束位置
        const lastBraceIndex = cleanResult.lastIndexOf('}')
        if (lastBraceIndex !== -1) {
          cleanResult = cleanResult.substring(0, lastBraceIndex + 1)
        }

        cleanResult = cleanResult.trim()
        console.log('清理后的JSON:', cleanResult)

        // 解析JSON结果
        const customerData = JSON.parse(cleanResult)

        // 使用统一的方法填充表单
        this.fillFormWithCustomerData(customerData)

        this.$notify({
          title: '成功',
          message: '客户信息已成功提取并填充到表单中',
          type: 'success',
          duration: 3000
        })

        // 清空输入框
        this.userInfoInput = ''
      } catch (error) {
        console.error('解析AI返回结果失败:', error)
        console.error('原始结果:', result)

        this.$notify({
          title: '解析错误',
          message: `AI返回的结果格式有误，无法解析客户信息: ${error.message}`,
          type: 'error',
          duration: 5000
        })

        // 如果是JSON格式错误，尝试手动提取一些基本信息
        this.tryManualExtraction(result)
      }
    },
    handleStartExtract() {
      if (!this.userInfoInput.trim()) {
        this.$notify({
          title: '提示',
          message: '请先输入客户信息或粘贴图片',
          type: 'warning',
          duration: 2000
        })
        return
      }

      // 调用AITask组件的显示对话框方法
      this.$refs.aiExtractTask.handleShowDialog()
    },
    tryManualExtraction(result) {
      // 作为备用方案，尝试手动从结果中提取信息
      try {
        console.log('尝试手动提取信息...')

        // 使用正则表达式尝试提取JSON部分
        const jsonMatch = result.match(/\{[\s\S]*?\}/)
        if (jsonMatch) {
          const jsonStr = jsonMatch[0]
          console.log('提取到的JSON:', jsonStr)

          const customerData = JSON.parse(jsonStr)

          // 如果成功解析，继续填充表单
          this.fillFormWithCustomerData(customerData)

          this.$notify({
            title: '成功',
            message: '客户信息已通过备用方式提取并填充到表单中',
            type: 'success',
            duration: 3000
          })

          this.userInfoInput = ''
        }
      } catch (manualError) {
        console.error('手动提取也失败了:', manualError)
      }
    },

    fillFormWithCustomerData(customerData) {
      // 将提取的信息填充到表单中
      if (customerData.name) {
        this.temp.name = customerData.name
      }
      if (customerData.company) {
        this.temp.company = customerData.company
      }
      if (customerData.domain) {
        this.temp.domain = customerData.domain
      }
      if (customerData.mail) {
        this.temp.mail = customerData.mail
      }
      if (customerData.phone) {
        this.temp.phone = customerData.phone
      }
      if (customerData.whatsapp) {
        this.temp.whatsapp = customerData.whatsapp
      }
      if (customerData.country) {
        this.temp.country = customerData.country
      }
      if (customerData.source) {
        this.temp.source = customerData.source
      }
      if (customerData.address) {
        this.temp.address = customerData.address
      }
      if (customerData.note) {
        this.temp.note = customerData.note
      }

      // 处理标签（如果AI返回了tag字段）
      if (customerData.tag) {
        if (typeof customerData.tag === 'string') {
          // 如果是字符串，按逗号分割
          const tags = customerData.tag.split(',').map(tag => tag.trim()).filter(tag => tag)
          this.temp.tag = [...new Set([...this.temp.tag, ...tags])] // 去重合并
        } else if (Array.isArray(customerData.tag)) {
          // 如果是数组，直接合并
          this.temp.tag = [...new Set([...this.temp.tag, ...customerData.tag])] // 去重合并
        }
      }
    },

    handlePaste(event) {
      console.log('粘贴事件触发')
      const data = event.clipboardData || window.clipboardData
      if (data) {
        // 先检查是否有文本内容，并尝试解析为图片URL
        const textContent = data.getData('text')
        if (textContent && this.isImageUrl(textContent)) {
          console.log('检测到图片URL:', textContent)
          // 直接将URL设置为输入内容
          this.userInfoInput = textContent
          this.$message.success('图片URL已粘贴')
          return
        }

        // 否则检查是否为实际图片文件
        const items = data.items
        console.log('剪贴板项目数量:', items.length)
        let foundImage = false
        for (let i = 0; i < items.length; i++) {
          console.log('项目类型:', items[i].kind, items[i].type)
          if (items[i].kind === 'file' && items[i].type.indexOf('image/') !== -1) {
            const blob = items[i].getAsFile()
            console.log('获取到图片文件:', blob)
            this.handleImageUpload(blob)
            foundImage = true
          }
        }
        if (!foundImage) {
          this.$message.warning('未检测到图片，请确保复制的是图片内容或图片URL')
        }
      } else {
        this.$message.error('无法获取剪贴板数据')
      }
    },

    // 检查字符串是否是图片URL
    isImageUrl(str) {
      // 检查是否是URL格式
      try {
        const url = new URL(str)
        // 检查URL是否指向图片
        const pathLower = url.pathname.toLowerCase()
        const isImageExt =
           pathLower.endsWith('.jpg') ||
           pathLower.endsWith('.jpeg') ||
           pathLower.endsWith('.png') ||
           pathLower.endsWith('.gif') ||
           pathLower.endsWith('.webp') ||
           pathLower.endsWith('.svg') ||
           pathLower.endsWith('.bmp')
        return isImageExt || /\.(jpg|jpeg|png|gif|webp|svg|bmp)/i.test(url.search)
      } catch (e) {
        return false
      }
    },

    // 处理图片上传
    handleImageUpload(blob) {
      if (!blob) {
        this.$message.error('图片文件无效')
        return
      }

      this.$message.info('正在处理图片...')
      this.isUploading = true

      const reader = new FileReader()
      reader.onload = (e) => {
        try {
          const base64Data = e.target.result

          // 检查文件大小（建议限制在10MB以内）
          if (blob.size > 10 * 1024 * 1024) {
            this.$notify({
              title: '错误',
              message: '图片文件过大，请选择小于10MB的图片',
              type: 'error',
              duration: 3000
            })
            this.isUploading = false
            return
          }

          // 将base64数据填充到输入框
          this.userInfoInput = base64Data

          this.$notify({
            title: '成功',
            message: `图片已转换为base64格式 (${(blob.size / 1024).toFixed(1)}KB)`,
            type: 'success',
            duration: 3000
          })

          console.log('图片转换完成:', {
            fileName: blob.name,
            fileSize: blob.size,
            fileType: blob.type,
            base64Length: base64Data.length
          })

          this.isUploading = false
        } catch (err) {
          console.error('处理图片失败:', err)
          this.$message.error('图片处理失败')
          this.isUploading = false
        }
      }

      reader.onerror = () => {
        console.error('读取文件失败')
        this.$message.error('读取文件失败')
        this.isUploading = false
      }

      // 开始转换
      reader.readAsDataURL(blob)
    },

    // 获取焦点
    focusPasteArea(event) {
      event.preventDefault()
    },

    handleDrop(event) {
      event.preventDefault()
      this.isDragging = false

      const data = event.dataTransfer
      if (data) {
        // 检查是否有文本内容，并尝试解析为图片URL
        const textContent = data.getData('text')
        if (textContent && this.isImageUrl(textContent)) {
          console.log('拖拽的图片URL:', textContent)
          // 直接将URL设置为输入内容
          this.userInfoInput = textContent
          this.$message.success('图片URL已添加')
          return
        }

        // 否则检查是否为实际图片文件
        const items = data.items
        let foundImage = false
        for (let i = 0; i < items.length; i++) {
          if (items[i].kind === 'file' && items[i].type.indexOf('image/') !== -1) {
            const blob = items[i].getAsFile()
            this.handleImageUpload(blob)
            foundImage = true
          }
        }

        if (!foundImage) {
          // 尝试从dataTransfer.files获取文件
          const files = data.files
          for (let i = 0; i < files.length; i++) {
            if (files[i].type.indexOf('image/') !== -1) {
              this.handleImageUpload(files[i])
              foundImage = true
            }
          }
        }

        if (!foundImage) {
          this.$message.warning('未检测到图片文件')
        }
      }
    },

    handleDragEnter(event) {
      event.preventDefault()
      this.isDragging = true
    },

    handleDragLeave(event) {
      event.preventDefault()
      // 只有当离开整个输入区域时才隐藏提示
      if (!event.currentTarget.contains(event.relatedTarget)) {
        this.isDragging = false
      }
    },
    handleAITaskClose() {
      // AI任务关闭时可以做一些清理工作
      console.log('AI任务关闭')
    }
  }
}
</script>

<style scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}

.top >>> .el-select .el-input {
  width: 350px;
}

.top >>> .input-with-select .el-input-group__prepend {
  background-color: #fff;
}

.top {
  padding-left: 20px;
  margin-bottom: 30px;
  margin-top: 28px;
}

.input-with-select {
  width: calc(100% - 200px);
}

.add-btn {
  float: right;
  margin-right: 20px;
  width: 150px
}

.mt-pagination {
  float: right;
  margin-top: 5px;
}

.app-container >>> .el-dialog {
  margin-top: 48px !important;
  margin-bottom: 68px;
}

.mt-dialog >>> .el-transfer-panel {
  width: calc(50% - 60px);
}

.mt-form >>> .el-select {
  width: 100%;
}

.mt-form >>> .el-input__inner {
  width: 100%;
}

.mt-dialog >>> .el-dialog {
  margin-top: 60px;
  /*margin: 168px auto !important;*/
}

.mt-dialog >>> .el-dialog__body {
  padding-bottom: 100px;
}

/* AI信息提取区域样式 */
.ai-extract-section {
  background-color: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  padding: 15px;
  margin: 5px 0;
  height: fit-content;
}

.ai-section-title {
  margin: 0 0 15px 0;
  color: #409EFF;
  font-size: 16px;
  font-weight: 600;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #e9ecef;
  padding-bottom: 8px;
}

.ai-section-title i {
  margin-right: 8px;
  font-size: 18px;
}

.ai-extract-section .el-textarea__inner {
  background-color: #ffffff;
  border: 1px solid #dcdfe6;
  font-family: Consolas, Monaco, 'Courier New', monospace;
  font-size: 13px;
  line-height: 1.4;
}

.ai-extract-section .el-textarea__inner:focus {
  border-color: #409EFF;
}

.ai-tip {
  font-size: 12px;
  color: #909399;
  margin-bottom: 15px;
  padding: 8px 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border-left: 3px solid #409EFF;
}

.ai-tip i {
  margin-right: 5px;
  color: #409EFF;
}

/* 粘贴区域样式 */
.paste-area {
  position: relative;
  padding: 10px;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  text-align: center;
  margin-bottom: 10px;
  cursor: pointer;
  background-color: #fafafa;
  transition: all 0.3s;
  min-height: 160px;
  outline: none;
}

.paste-area:hover,
.paste-area:focus {
  border-color: #409EFF;
  background-color: #f5f7fa;
}

.paste-tip {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 60px;
  margin-bottom: 10px;
}

.paste-tip i {
  font-size: 24px;
  color: #909399;
  margin-bottom: 5px;
}

.paste-tip div {
  color: #606266;
  font-size: 14px;
}

.input-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 10px; /* 减去 margin-bottom */
  background-color: rgba(64, 158, 255, 0.1);
  border: 2px dashed #409EFF;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: 10;
  pointer-events: none;
}

.input-overlay i {
  font-size: 32px;
  color: #409EFF;
  margin-bottom: 8px;
}

.input-overlay span {
  color: #409EFF;
  font-size: 14px;
  font-weight: bold;
}
</style>
